package base.thread.pools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 仿写连接池
 */
public class ConnctionPool {

    int size;//连接池大小
    List<Connection> cs = new ArrayList<>();

    public ConnctionPool(int size) {
        this.size = size;
        init();
    }

    void init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < size; i++) {
                Connection c = DriverManager.getConnection(
                        "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=UTF-8",
                        "root",
                        "123");
                cs.add(c);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //获得连接的方法
    synchronized Connection getConnection() {
        while (cs.isEmpty()) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Connection c = cs.remove(0);
        return c;
    }

    //回收连接的方法
    synchronized void returnConnection(Connection c) {
        cs.add(c);
        this.notifyAll();
    }

}
